package com.wx.spring.mvc;

import com.wx.spring.annotations.MyModelAttribute;
import com.wx.spring.exception.SpringMvcException;
import com.wx.spring.utils.AnnotationUtils;
import com.wx.spring.utils.ConvertUtis;
import com.wx.spring.utils.MyStringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Objects;

/**
 * @ClassName BindingByMyModelAttribute
 * @Author wx
 * @Description 获取注解MyModelAttribute绑定的对象
 * @Date 2019-01-30-18:36
 */
@Slf4j
public class BindingByMyModelAttribute implements BindingParamter {

    /**
     * @methodName: getBindingParamter
     * @author: wx
     * @description: 获取绑定参数对应的对象
     * @param parameter
     * @param request
     * @date: 2019/1/30
     * @return: java.lang.Object
     */
    @Override
    public Object getBindingParamter(Parameter parameter, HttpServletRequest request) throws IllegalAccessException, InstantiationException, NoSuchMethodException {
        MyModelAttribute myModelAttribute = parameter.getAnnotation(MyModelAttribute.class);
        Class<?> aClass = parameter.getType();
        if (AnnotationUtils.isNotEmpty(myModelAttribute) && aClass != null) {
            if (!Objects.equals(aClass.getSimpleName(), myModelAttribute.value())) {
                throw new SpringMvcException("实体类绑定异常，请重新检查");
            }
            //获取所有属性
            Field[] fields = aClass.getDeclaredFields();
            Object object = aClass.newInstance();
            for (Field field : fields) {
                String parameter1 = request.getParameter(field.getName());
                if (MyStringUtils.isNotEmpty(parameter1)) {
                    Object setObject = ConvertUtis.convert(field.getType().getSimpleName(), parameter1);
                    String methodName = ConvertUtis.getSetMethodNameByField(field.getName());
                    Method method = aClass.getMethod(methodName, field.getType());
                    try {
                        method.invoke(object, setObject);
                    } catch (InvocationTargetException e) {
                        log.error("{}属性赋值异常", field.getName());
                        e.printStackTrace();
                        throw new SpringMvcException("属性赋值异常");
                    }
                }
            }
            return object;
        }

        return null;
    }
}
